class GenTable {
    constructor(opts) {
        // 普通牌：万，筒，条
        this.KeyDic = {};
        this.KeyDicWithGhost = {};
        for (let i = 1; i < 9; i++) {
            this.KeyDicWithGhost[i] = {};
        }
    }

    static Instance() {
        if (!GenTable.instance) {
            let instance = new GenTable();
            instance.init();
            GenTable.instance = instance;
        }
        return GenTable.instance;
    }

    init() {
		this.load();
    }

    findCards(cards, ghostCount) {
        let key = this.generateKey(cards);
        if (ghostCount > 0) {
            if (this.KeyDicWithGhost[ghostCount][key]) {
                return true;
            }
        }
		else if (this.KeyDic[key]) {
            return true;
        }
        return false;
    }

    load() {
        // 不带鬼
        this._load('Table0', this.KeyDic);
        // 带鬼
        for (let i = 1; i < 9; i++) {
            this._load('Table' + i, this.KeyDicWithGhost[i]);
        }
    }

    _load(fileName, keyDic) {
		setTimeout(() => {
			cc.loader.loadRes('tbl/'+fileName, (err, jsonAssert) => {
				if (err) {
					console.log(`load tbl/${fileName} error`);
				}
				else {
					for (let item of jsonAssert.json.data) {
						keyDic[item] = 1;
					}
				}
			});
		}, 0);
    }

    toNumberArray(strKey) {
        let result = [];
        for (let i = 0; i < strKey.length; i++) {
            let temp = strKey.slice(i, i + 1);
            result.push(parseInt(temp));
        }
        return result;
    }

    generateKey(cards) {
        let key = '';
        let dic = ['0', '1', '2', '3', '4']
        for (let i = 0; i < cards.length; i++) {
            key = key + dic[cards[i]];
        }
        return key;
    }

    calTotalCardCount(cards) {
        let count = 0;
        for (let i = 0; i < 9; i++) {
            count += cards[i];
        }
        return count;
    }
}

module.exports = GenTable;

